<template>
  <a-radio-group
    placeholder="请选择"
    v-model="selectValue"
    allow-clear
    @change="onChange"
    v-bind="$attrs"
  >
    <slot :options="optionDatas">
      <a-radio
        :key="item[labelValue]"
        :value="item[labelValue]"
        :item="item"
        v-for="item in optionDatas"
      >
        {{ item[label] }}
      </a-radio>
    </slot>
  </a-radio-group>
</template>
<script>
import { post, get } from 'server/axios'
import { debounce } from 'lodash'
import { evalPropChain } from 'utils/utils.js'
const AXIOS_METHOD = {
  get: get,
  post: post
}
export default {
  name: 'CpsRadioGroup',
  props: {
    value: {
      type: [String, Number, Array],
      default: undefined
    },
    url: {
      type: String,
      default: ''
    },
    // 下拉框显示的文本字段
    label: {
      type: String,
      default: 'label'
    },
    // 下拉框值的字段
    labelValue: {
      type: String,
      default: 'value'
    },
    // 请求接口参数
    params: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 支持自定义传options
    options: {
      type: Array,
      default: () => []
    },
    method: {
      type: String,
      default: 'post'
    },
    respField: {
      type: String,
      default: 'data'
    },
    immediate: {
      type: Boolean,
      default: false
    }
  },
  emits: ['input', 'update:options'],
  data() {
    return {
      reqParams: this.params,
      optionDatas: this.options || []
    }
  },
  computed: {
    selectValue: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },
  watch: {
    params(newV, v) {
      if (JSON.stringify(newV) !== JSON.stringify(v)) {
        if (this.url) {
          this.reqParams = this.params
          this.queryServiceData()
        }
      }
    },
    immediate: {
      handler(val) {
        if (this.url && this.immediate) {
          this.queryServiceData()
        }
      },
      immediate: true
    }
  },
  methods: {
    isNumber(val) {
      return parseFloat(val) !== 'NaN'
    },
    getRquerstURL() {
      return this.url.startsWith('http')
        ? this.url
        : `${process.env.VUE_APP_CONFIG}/${this.url}`
    },
    async queryServiceData() {
      const serverURL = this.getRquerstURL()
      const resp = await AXIOS_METHOD[this.method.toLowerCase()](
        serverURL,
        this.reqParams
      )
      const data = evalPropChain(resp, this.respField)
      if (Object.prototype.toString.call(data) === '[object Object]') {
        this.optionDatas = Object.keys(data).map(key => {
          return {
            label: data[key],
            value: this.isNumber(key) ? parseInt(key) : key
          }
        })
      } else {
        this.optionDatas = data
      }

      this.$emit('update:options', this.optionDatas)
      this.$forceUpdate()
    },
    onChange(value, option) {
      this.$emit('change', value, option)
    }
  }
}
</script>
